package mia.beans;

import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.event.ActionEvent;

import mia.dao.UserEntityDAO;
import mia.entity.UserEntity;
import mia.util.DigesterUtil;
import mia.util.HibernateManager;

@ManagedBean(name="userRegBean")
@RequestScoped
public class UserRegBean {

	private UserEntity user = new UserEntity();
	private String registerStatus = "";
	private String email2;
	private String password2;

	public UserEntity getUser() {
		return user;
	}
	public void setUser(UserEntity user) {
		this.user = user;
	}

	public String getRegisterStatus() {
		return registerStatus;
	}
	public void setRegisterStatus(String registerStatus) {
		this.registerStatus = registerStatus;
	}
	public String getEmail2() {
		return email2;
	}
	public void setEmail2(String email2) {
		this.email2 = email2;
	}
	public String getPassword2() {
		return password2;
	}
	public void setPassword2(String password2) {
		this.password2 = password2;
	}	

	public void tryRegister(ActionEvent actionEvent)
	{
		
		if(!this.email2.equals(user.getEmail()))
		{
			this.setRegisterStatus("Adresy e-mail się nie zgadzają.");
			new mia.msgs.MessagesController().addError(actionEvent, this.getRegisterStatus());
		}
		else
			if(email_validate(user.getEmail()))
			{
			if(this.password2.equals(user.getPassword()))
		{
			boolean userExists = UserEntityDAO.checkIfUserExists(user.getLogin(), user.getEmail());
			if(userExists)
			{
				this.setRegisterStatus("Niepowodzenie: użytkownik o podanym adresie e-mail lub loginie istnieje.");
				new mia.msgs.MessagesController().addError(actionEvent, this.getRegisterStatus());
			}
			else
			{
				user.setPassword(DigesterUtil.getDigest(user.getPassword()));
				user.setRegDate(new Date());
			 	user.setAdmin(false);
			 	user.setActive(true);
			 	if(HibernateManager.trySave(user))
			 	{
			 		this.setRegisterStatus("Zarejestrowano!");
					new mia.msgs.MessagesController().addInfo(actionEvent, this.getRegisterStatus());
			 	}
			}
		}
			else
			{
				this.setRegisterStatus("Hasła się nie zgadzają.");
				new mia.msgs.MessagesController().addError(actionEvent, this.getRegisterStatus());
			}
			}
			else
			{
				this.setRegisterStatus("Niepoprawny format adresu e-mail.");
				new mia.msgs.MessagesController().addError(actionEvent, this.getRegisterStatus());
			}
		//return "result";
	}
	
	private Boolean email_validate(String email)
	{
		Pattern p = Pattern.compile(".+@.+\\.[a-z]+");
		Matcher m = p.matcher(email);
		if(m.matches())
			return true;
		else
			return false;
	}
	
}
